import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@store'
import cache from '@cache'
import {
  IS_LOGIN
} from '@store/mutation-types'

import publicRoutes from './modules/'

import {
  getToken
} from '@cache'

Vue.use(VueRouter)

const routes = [
  ...publicRoutes
]

const router = new VueRouter({
  routes,
  mode: (process.env.NODE_ENV === 'development') ? 'hash' : 'hash',
  base: '/admin/',
  history: true,
  saveScrollPosition: true,
  transitionOnLoad: true,
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

router.beforeEach(({ meta, path, query }, from, next) => {
  const { auth = true } = meta
  const isLogin = getToken() ? true : false
  if (auth) {
    if (!isLogin) {
      store.commit(IS_LOGIN, false)
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
